package com.edu.thread.sync;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class PrintAB_02 {

    public static void main(String[] args) {
        Data data = new Data();
        Runnable runnableA = new Runnable() {
            @Override
            public void run() {
                data.printA();
            }
        };

        Runnable runnableB = new Runnable() {
            @Override
            public void run() {
                data.printB();
            }
        };

        new Thread(runnableA).start();
        new Thread(runnableB).start();

    }
}

class Data {
    private boolean flag = true;
    ReentrantLock lock = new ReentrantLock();
    Condition condition = lock.newCondition();

    public void printA() {
        while (true) {
            try {
                lock.lock();
                while (!flag) {
                    try {
                        condition.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("A");
                flag = false;
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                condition.signal();
            } finally {
                lock.unlock();
            }
        }

    }

    public void printB() {
        while (true) {
            try {
                lock.lock();
                while (flag) {
                    try {
                        condition.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("B");
                flag = true;
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                condition.signalAll();
            } finally {
                lock.unlock();
            }
        }
    }
}
